/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.yelevatordevice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceChangeTypeEnum;
import vip.xiaonuo.facedoor.modular.device.listener.DevicePublisher;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceSourceEnum;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant.*;
import vip.xiaonuo.modular.remoteapi.stairs.response.DeviceDTO;
import vip.xiaonuo.modular.sync.BuildingAddEvent;
import vip.xiaonuo.modular.sync.DeviceEvent;
import vip.xiaonuo.modular.ybuildingmemberrl.entity.YBuildingMemberRl;
import vip.xiaonuo.modular.ybuildingmemberrl.service.YBuildingMemberRlService;
import vip.xiaonuo.modular.ybuildingvisitorrl.entity.YBuildingVisitorRl;
import vip.xiaonuo.modular.ybuildingvisitorrl.mapper.YBuildingVisitorRlMapper;
import vip.xiaonuo.modular.ybuliding.entity.YBuliding;
import vip.xiaonuo.modular.ybuliding.service.YBulidingService;
import vip.xiaonuo.modular.ydeviceevent.entity.YDeviceEvent;
import vip.xiaonuo.modular.ydeviceevent.mapper.YDeviceEventMapper;
import vip.xiaonuo.modular.yelevatordevice.entity.YElevatorDevice;
import vip.xiaonuo.modular.yelevatordevice.enums.YElevatorDeviceExceptionEnum;
import vip.xiaonuo.modular.yelevatordevice.mapper.YElevatorDeviceMapper;
import vip.xiaonuo.modular.yelevatordevice.param.YElevatorDeviceParam;
import vip.xiaonuo.modular.yelevatordevice.service.YElevatorDeviceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.ymemberrecord.mapper.YMemberRecordMapper;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 梯控设备service接口实现类
 *
 * @author 胡鹏达
 * @date 2022-08-29 10:47:04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class YElevatorDeviceServiceImpl extends ServiceImpl<YElevatorDeviceMapper, YElevatorDevice> implements YElevatorDeviceService {
    @Autowired
    private ApplicationEventPublisher publisher;


    @Resource
    private YElevatorDeviceMapper mapper;

    @Resource
    private YDeviceEventMapper deviceEventMapper;

    @Resource
    private YMemberRecordMapper yMemberRecordMapper;

    @Resource
    private DevicePublisher devicePublisher;

    @Resource
    private YBulidingService yBulidingService;


    public void syncPerson(YElevatorDeviceParam elevatorDevice) {
        YElevatorDevice dbDevice = this.getById(elevatorDevice.getId());
        if (!Objects.equals(dbDevice.getFiledStatus(), RemoteStairsConstant.ElevatorFiledStatus.SYNC)) {
            throw new ServiceException(500, "设备参数未同步，请先同步设备参数！");
        }
        if (dbDevice.getBuildingId() == null) {
            throw new ServiceException(500, "尚未选择楼栋无法进行人员同步，请先选择楼栋！");
        }
        // 新增人员中
        dbDevice.setMemberSyncStatus(RemoteStairsConstant.MemberSyncStatus.ADD);
        this.updateById(dbDevice);//保存
        // 新增人员事件
        publisher.publishEvent(new BuildingAddEvent(new Object(), elevatorDevice.getBuildingId(), elevatorDevice.getId()));
    }

    @Override
    public SuccessResponseData syncDeviceTime(YElevatorDeviceParam elevatorDevice) {
        YElevatorDevice device = this.getById(elevatorDevice.getId());
        YDeviceEvent eventEntity = deviceEventMapper.selectAllNeqEnd(device.getDeviceNo(), RemoteStairsConstant.RequestCmd.UPDATE_SYSTEM_TIME);
        if (eventEntity != null) {
            throw new ServiceException(500, "同步时间中请稍后！");
        }
        // 保存任务
        YDeviceEvent deviceEvent = new YDeviceEvent();
        deviceEvent.setDeviceNo(device.getDeviceNo());
        deviceEvent.setStatus(DeviceEvent.NEW);
        deviceEvent.setType(RemoteStairsConstant.RequestCmd.UPDATE_SYSTEM_TIME);
        deviceEvent.setCreateDate(new Date());
        deviceEventMapper.insert(deviceEvent);
        return new SuccessResponseData();
    }

    public YElevatorDevice getByParam(YElevatorDevice elevatorDevice) {
        return mapper.getByParam(elevatorDevice);
    }

    public void fire(YElevatorDeviceParam elevatorDevice) {
        YElevatorDevice db = this.getById(elevatorDevice);
        if (Objects.equals(db.getFire(), "TRUE")) {
            throw new ServiceException(500, "消防已经开启、无需再次开启！");
        }
        YDeviceEvent deviceEvent = new YDeviceEvent();
        deviceEvent.setDeviceNo(elevatorDevice.getDeviceNo());
        deviceEvent.setType(RemoteStairsConstant.RequestCmd.SET_FIRE);
        deviceEvent.setCreateDate(new Date());
        deviceEvent.setBody("TRUE");
        deviceEvent.setStatus(DeviceEvent.NEW);
        deviceEventMapper.insert(deviceEvent);
    }

    @Override
    public void unFire(YElevatorDeviceParam elevatorDevice) {
        YElevatorDevice db = this.getById(elevatorDevice);
        if (Objects.equals(db.getFire(), "FALSE") || StringUtils.isBlank(db.getFire())) {
            throw new ServiceException(500, "消防已经关闭、无需再次关闭！");
        }
        YDeviceEvent deviceEvent = new YDeviceEvent();
        deviceEvent.setDeviceNo(elevatorDevice.getDeviceNo());
        deviceEvent.setType(RemoteStairsConstant.RequestCmd.SET_FIRE);
        deviceEvent.setCreateDate(new Date());
        deviceEvent.setBody("FALSE");
        deviceEvent.setStatus(DeviceEvent.NEW);
        deviceEventMapper.insert(deviceEvent);
    }

    @Override
    public void listPersons(YElevatorDeviceParam elevatorDevice) {
        yMemberRecordMapper.deleteByDeviceId(elevatorDevice.getDeviceNo());
        YDeviceEvent eventEntity = new YDeviceEvent();
        eventEntity.setStatus(DeviceEvent.NEW);
        eventEntity.setType(RemoteStairsConstant.RequestCmd.BROWSE_PERSONS);
        eventEntity.setBody("1");
        eventEntity.setCreateDate(new Date());
        eventEntity.setDeviceNo(elevatorDevice.getDeviceNo());
        deviceEventMapper.insert(eventEntity);
    }

    public void syncFiled(YElevatorDeviceParam elevatorDevice) {
        YElevatorDevice yElevatorDevice = this.getById(elevatorDevice.getId());

        try {
            YDeviceEvent eventEntity = deviceEventMapper.selectAllNeqEnd(yElevatorDevice.getDeviceNo(), RemoteStairsConstant.RequestCmd.REQUEST_DEVICE_PARAMS);
            if (eventEntity != null) {
                throw new ServiceException(500, "属性同步中 请稍后");
            }
            // 保存系统事件
            YDeviceEvent saveBean = new YDeviceEvent();
            saveBean.setType(RemoteStairsConstant.RequestCmd.REQUEST_DEVICE_PARAMS);
            saveBean.setCreateDate(new Date());
            saveBean.setStatus(DeviceEvent.NEW);
            saveBean.setDeviceNo(yElevatorDevice.getDeviceNo());
            deviceEventMapper.insert(saveBean);
            yElevatorDevice.setFiledStatus(RemoteStairsConstant.ElevatorFiledStatus.CUR_SYNC);
            this.updateById(yElevatorDevice);
        } catch (Exception e) {
            throw new ServiceException(500, "属性同步失败" + ExceptionUtils.getMessage(e));
        }
    }

    @Override
    public PageResult<YElevatorDevice> page(YElevatorDeviceParam yElevatorDeviceParam) {
        return new PageResult<>(mapper.findList(PageFactory.defaultPage(), yElevatorDeviceParam));
    }

    @Override
    public List<YElevatorDevice> list(YElevatorDeviceParam yElevatorDeviceParam) {
        return this.list();
    }

    @Override
    public void add(YElevatorDeviceParam yElevatorDeviceParam) {
        YElevatorDevice yElevatorDevice = new YElevatorDevice();
        BeanUtil.copyProperties(yElevatorDeviceParam, yElevatorDevice);
        this.save(yElevatorDevice);
        devicePublisher.publishEvent(DeviceChangeTypeEnum.ADD, DeviceSourceEnum.TRAILS, yElevatorDevice);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(YElevatorDeviceParam yElevatorDeviceParam) {
        YElevatorDevice dbBean = this.getById(yElevatorDeviceParam.getId());
        if (dbBean.getLastUpTime() == null) {
            this.removeById(dbBean);
            return;
        }
        List<YDeviceEvent> yDeviceEvents = deviceEventMapper.selectList(new LambdaQueryWrapper<YDeviceEvent>().eq(YDeviceEvent::getStatus, DeviceEvent.NEW).eq(YDeviceEvent::getType, RequestCmd.DELETE_ALL_PERSON)
                .eq(YDeviceEvent::getDeviceNo, dbBean.getDeviceNo()));
        if (CollectionUtil.isNotEmpty(yDeviceEvents)) {
            throw new ServiceException(500, "正在删除中！ 请勿执行相同操作!");
        }
        YDeviceEvent eventEntity = new YDeviceEvent();
        eventEntity.setStatus(DeviceEvent.NEW);
        eventEntity.setType(RequestCmd.DELETE_ALL_PERSON);
        eventEntity.setCreateDate(new Date());
        eventEntity.setDeviceNo(dbBean.getDeviceNo());
        deviceEventMapper.insert(eventEntity);
        devicePublisher.publishEvent(DeviceChangeTypeEnum.DELETE, DeviceSourceEnum.TRAILS, dbBean);

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteNow(YElevatorDeviceParam yElevatorDeviceParam) {
        YElevatorDevice dbBean = this.getById(yElevatorDeviceParam.getId());
        if (dbBean.getLastUpTime() == null) {
            this.removeById(dbBean);
            return;
        }
        List<YDeviceEvent> yDeviceEvents = deviceEventMapper.selectList(new LambdaQueryWrapper<YDeviceEvent>().eq(YDeviceEvent::getStatus, DeviceEvent.NEW).eq(YDeviceEvent::getType, RequestCmd.DELETE_ALL_PERSON)
                .eq(YDeviceEvent::getDeviceNo, dbBean.getDeviceNo()));
        if (CollectionUtil.isNotEmpty(yDeviceEvents)) {
            throw new ServiceException(500, "正在删除中！ 请勿执行相同操作!");
        }
        // 人员删除全部记录信息
        memberDeleteAllPerson(dbBean);
        VisitorDeleteAllPerson(dbBean);
    }


    @Autowired
    private YBuildingMemberRlService buildingMemberService;

    @Resource
    private YBuildingVisitorRlMapper buildingVisitorRlMapper;

    @Resource
    private YMemberRecordMapper memberRecordMapper;

    private void VisitorDeleteAllPerson(YElevatorDevice elevatorDevice) {
        // 中间表删除全部信息
        buildingVisitorRlMapper.delete(new LambdaQueryWrapper<YBuildingVisitorRl>().eq(YBuildingVisitorRl::getDeviceId, elevatorDevice.getId()));
    }

    private void memberDeleteAllPerson(YElevatorDevice elevatorDevice) {
        // 中间表删除全部信息
        buildingMemberService.remove(new LambdaQueryWrapper<YBuildingMemberRl>().eq(YBuildingMemberRl::getDeviceId, elevatorDevice.getId()));
        // 删除设备信息
        this.removeById(elevatorDevice);
        // 人员历史表删除全部信息
        memberRecordMapper.deleteByDeviceId(elevatorDevice.getDeviceNo());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(YElevatorDeviceParam yElevatorDeviceParam) {
        YElevatorDevice dbDevice = this.queryYElevatorDevice(yElevatorDeviceParam);
        BeanUtil.copyProperties(yElevatorDeviceParam, dbDevice);
        if (Objects.equals(dbDevice.getFiledStatus(), RemoteStairsConstant.ElevatorFiledStatus.NO_SYNC)) {
            throw new ServiceException(500, "设备参数未同步，请同步设备参数！");
        }
        if (yElevatorDeviceParam.getBuildingId() == null) {
            throw new ServiceException(500, "设备参数未同步，请选择设备归属区域！");
        }
        YBuliding buliding = yBulidingService.getById(yElevatorDeviceParam.getBuildingId());


        if (StringUtils.isNotBlank(dbDevice.getMemberSyncStatus()) && !Objects.equals(dbDevice.getMemberSyncStatus(), MemberSyncStatus.SUCCESS)) {
            throw new ServiceException(500, "设备忙碌中！");
        }
        // 梯控楼栋发生变更
        if (!Objects.equals(dbDevice.getBuildingId(), yElevatorDeviceParam.getBuildingId())) {
            // 所属建筑发生变更
            if (dbDevice.getBuildingId() != null) {
                throw new ServiceException(500, "不允许变更设备楼栋信息！请删除后重新操作！");
            } else {
                // 新增人员中
                dbDevice.setMemberSyncStatus(MemberSyncStatus.ADD);
                this.updateById(dbDevice);
                // 新增人员事件
                publisher.publishEvent(new BuildingAddEvent(new Object(), dbDevice.getBuildingId(), dbDevice.getId()));
            }
        }
        if (yElevatorDeviceParam.getControDevice() != null && yElevatorDeviceParam.getControDevice()) {
            // 保存事件
            DeviceDTO.ServerInfoDTO serverInfoDTO = new DeviceDTO.ServerInfoDTO();
            serverInfoDTO.setServer_ip(yElevatorDeviceParam.getIp());
            if (yElevatorDeviceParam.getPort() != null) {
                serverInfoDTO.setServer_port(Integer.valueOf(yElevatorDeviceParam.getPort()));
            }
            serverInfoDTO.setServer_enable(Boolean.TRUE);
            DeviceDTO.DeviceInfoDTO deviceInfoDTO = new DeviceDTO.DeviceInfoDTO();
            if (StringUtils.isNotBlank(yElevatorDeviceParam.getFirstFloor())) {
                deviceInfoDTO.setFirst_floor(Integer.valueOf(yElevatorDeviceParam.getFirstFloor()));
            }
            if (StringUtils.isNotBlank(yElevatorDeviceParam.getDelayTime())) {
                deviceInfoDTO.setDelay_time(Integer.valueOf(yElevatorDeviceParam.getDelayTime()));
            }
            if (StringUtils.isNotBlank(yElevatorDeviceParam.getVolume())) {
                deviceInfoDTO.setVolume(Integer.valueOf(yElevatorDeviceParam.getVolume()));
            }
            if (StringUtils.isNotBlank(yElevatorDeviceParam.getVolume())) {
                deviceInfoDTO.setVolume(Integer.valueOf(yElevatorDeviceParam.getVolume()));
            }
            if (StringUtils.isNotBlank(yElevatorDeviceParam.getRemind())) {
                deviceInfoDTO.setRemind(Integer.valueOf(yElevatorDeviceParam.getRemind()));
            }
            deviceInfoDTO.setQr_mode(1);
            deviceInfoDTO.setBuildNumber(buliding.getCode());
            DeviceDTO.CardInfoDTO cardInfoDTO = new DeviceDTO.CardInfoDTO();
            cardInfoDTO.setPrevent_copy(yElevatorDeviceParam.getPreventCopy());
            DeviceDTO.CommonFloorDTO commonFloorDTO = new DeviceDTO.CommonFloorDTO();
            if (StringUtils.isNotBlank(yElevatorDeviceParam.getCommFloor())) {
                List<Integer> collect = Arrays.stream(yElevatorDeviceParam.getCommFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
                commonFloorDTO.setFloor(collect);
                commonFloorDTO.setComm_count(collect.size());
                commonFloorDTO.setComm_count(collect.size());
            } else {
                commonFloorDTO.setComm_count(0);
                commonFloorDTO.setComm_count(0);
            }
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setDevice_info(deviceInfoDTO).setCard_info(cardInfoDTO).setCommon_floor(commonFloorDTO).setServer_info(serverInfoDTO);

            YDeviceEvent saveBean = new YDeviceEvent();
            saveBean.setBody(JSON.toJSONString(deviceDTO));
            saveBean.setDeviceNo(dbDevice.getDeviceNo());
            saveBean.setStatus(DeviceEvent.NEW);
            saveBean.setCreateDate(new Date());
            saveBean.setType(RequestCmd.UPDATE_DEVICE_PARAMS);
            deviceEventMapper.insert(saveBean);
        }
        this.updateById(dbDevice);//保存
        devicePublisher.publishEvent(DeviceChangeTypeEnum.EDIT, DeviceSourceEnum.TRAILS, dbDevice);

    }

    @Override
    public YElevatorDevice detail(YElevatorDeviceParam yElevatorDeviceParam) {
        return this.queryYElevatorDevice(yElevatorDeviceParam);
    }


    /**
     * 获取梯控设备
     *
     * @author 胡鹏达
     * @date 2022-08-29 10:47:04
     */
    private YElevatorDevice queryYElevatorDevice(YElevatorDeviceParam yElevatorDeviceParam) {
        YElevatorDevice yElevatorDevice = this.getById(yElevatorDeviceParam.getId());
        if (ObjectUtil.isNull(yElevatorDevice)) {
            throw new ServiceException(YElevatorDeviceExceptionEnum.NOT_EXIST);
        }
        return yElevatorDevice;
    }
}
